/*
 *   Copyright 1999-2016 Asiainfo Technologies(China),Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.asiainfo.redis.service.clusterhandler;

import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.RedisNode;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Protocol;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @version v 1.0 on 2016/5/19 17:00
 * @auther william.xu
 */
public class AddOldMasterNodesAsSlave {

    private RedisClusterHandler redisClusterHandler;
    private List<RedisClusterNode> masterList;
    private List<RedisClusterNode> slaveList;
    private Map<RedisClusterNode, Collection<RedisClusterNode>> masterSlaveMap;

    public AddOldMasterNodesAsSlave(RedisClusterHandler redisClusterHandler, List<RedisClusterNode> masterList,
                                    List<RedisClusterNode> slaveList, Map<RedisClusterNode,
            Collection<RedisClusterNode>> masterSlaveMap) {
        this.redisClusterHandler = redisClusterHandler;
        this.masterList = masterList;
        this.slaveList = slaveList;
        this.masterSlaveMap = masterSlaveMap;

    }

    public Object doInRedisCluster(RedisClusterConnection connection) throws Exception {
        //把原来的master节点meet到新的集群
        RedisNode redisNode = slaveList.get(0);
        Jedis jedis = new Jedis(redisNode.getHost(), redisNode.getPort(), Protocol.DEFAULT_TIMEOUT);
        for (RedisClusterNode node : masterList) {
            jedis.clusterMeet(node.getHost(), node.getPort());
        }
        jedis.close();
        redisClusterHandler.checkAllMeeting(connection);

        Iterator<RedisClusterNode> iterator = masterSlaveMap.keySet().iterator();
        while (iterator.hasNext()) {
            RedisClusterNode slave = iterator.next();//原来的master，新的cluster中的slave
            RedisClusterNode slaveNode = new RedisClusterNode(slave.getHost(), slave.getPort());
            RedisClusterNode master = masterSlaveMap.get(slave).iterator().next();
            //原来的slave，新的cluster中的master，保证是一个
            RedisClusterNode masterNode = new RedisClusterNode(master.getHost(), master.getPort());
            connection.clusterReplicate(masterNode, slaveNode);
        }
        return null;
    }

}
